﻿package nl.sanity.puremvc.model 
{
	import nl.sanity.debug.LogConsole;
	import nl.sanity.events.QueueLoaderEvent;
	import nl.sanity.net.LoadItem;
	import nl.sanity.net.QueueLoader;
	import nl.sanity.puremvc.Notifications;
	
	import org.puremvc.as3.utilities.startupmanager.interfaces.IStartupProxy;

	/**
	 * AssetProxy
	 * Loads all initial assets using an instance of the QueueLoader class.
	 * 
	 * @langversion ActionScript 3
	 *
	 * @author A. Gosman
	 * @since  28/03/2009
	 */
    public class AssetProxy extends EntityProxy implements IStartupProxy
    {
		public static const NAME		: String 		= "AssetProxy";
		public static const SRNAME		: String 		= "AssetSRProxy";
		
		protected var _name				: String;
		protected var _srName			: String;
		protected var _loader			: QueueLoader;
		
		// --- CONSTRUCTOR ----------------------------------------

		public function AssetProxy( name:String, srName:String )
        {
			_name 		= name || AssetProxy.NAME;
			_srName		= srName || AssetProxy.SRNAME; 
			
            super ( _name );
			
			setupQueueLoader();
        }
        
        
        // --- GETTERS / SETTERS ----------------------------------------
        
        public function get loader():QueueLoader
        {
        	return _loader;
        }
        
		
		// --- PUBLIC FUNCTIONS ----------------------------------------

		public function addAsset ( url:String, id:String, preventCache:Boolean = false ):void
		{
			LogConsole.info ( "AssetProxy.addAsset | url: " + url + " id: " + id );
			_loader.addItem( new LoadItem( url, id ) );
		}
		
		
		public function getAsset( id:String ):*
		{
			//LogConsole.info ( "AssetProxy.getAsset: " + id );
			
			//_loader.( id );
		}
		
		public function load():void
		{
			//LogConsole.info ( "AssetProxy.load" );
			
			_loader.start();
		}
		
		// --- PROTECTED FUNCTIONS ----------------------------------------

		protected function setupQueueLoader():void
		{
			_loader 		= new QueueLoader();
			_loader.addEventListener( QueueLoaderEvent.ON_ITEM_LOAD_ERROR, onLoadError, false, 0, true );
			_loader.addEventListener ( QueueLoaderEvent.ON_LOAD_COMPLETE, onLoadComplete, false, 0, true );
			//_loader.addEventListener( QueueLoaderEvent.ON_LOAD_PROGRESS, onLoadProgress, false, 0, true );
		}
		
		protected function onLoadProgress( event:QueueLoaderEvent ):void 
		{
			//LogConsole.info( "AssetProxy.onLoadProgress: " + _loader.bytesLoaded );
		}
		
		protected function onLoadComplete( event:QueueLoaderEvent ):void
		{
			sendLoadedNotification( Notifications.STARTUP_RESOURCE_LOADING_COMPLETED, _name, _srName );
		}

		protected function onLoadError( error:QueueLoaderEvent ):void
		{
			LogConsole.error( "Asset could not be loaded | " + error.toString() );
			sendLoadedNotification( Notifications.STARTUP_RESOURCE_LOADING_FAILED, _name, _srName );
		}
	}
}